#!/usr/bin/python
# -*- coding: utf-8 -*-  
"""
@Project : hello 
@file : job_runner.py
@Author : sheen
@time : 2025/5/28 15:18
@func :
"""
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
from mysql_demo import MySQLHelper
from job_state_manager import JobStateManager


class JobRunner:
    def __init__(self):
        self.state_manager = JobStateManager()
        self.rerun_flag: Dict[Tuple[str, int], bool] = {}

    def rerun_job(self, db: MySQLHelper, bu: str, job_id: int, force: bool = False) -> None:
        """执行单个任务重跑"""
        flag = self.check_job_rerun_required(db, bu, job_id)
        if flag or force:
            self.state_manager.backup_original_state(db, bu, job_id)
            cron = self.generate_cron_text()
            sql = f"""
                UPDATE asw_etl_{bu}_job.XX_SCHEDULE_JOB
                SET STATUS=1, RESTART=1, CRON='{cron}' WHERE job_id = {job_id} ;
            """
            db.execute(sql)

    def batch_rerun(self, db: MySQLHelper, bu: str, job_ids: List[int], force: bool = False) -> None:
        for job_id in job_ids:
            self.rerun_job(db, bu, job_id, force)

    @staticmethod
    def generate_cron_text(delay_seconds: int = 20) -> str:
        future_time = datetime.now() + timedelta(seconds=delay_seconds) - timedelta(hours=8)
        return f"{future_time.second} {future_time.minute} {future_time.hour} * * ?"

    def check_job_rerun_required(self, db: MySQLHelper, bu: str, job_id: int) -> bool:
        sql = f"SELECT STATUS FROM asw_etl_{bu}_job.XX_JOB_LOG WHERE job_id={job_id} ORDER BY created_time DESC LIMIT 1;"
        res = db.query(sql)
        return res and res[0]['STATUS'] == 'F'


if __name__ == '__main__':
    runner = JobRunner()
    print(runner.generate_cron_text())
